package com.health.healthproject.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.health.healthproject.entity.User;
import com.health.healthproject.mapper.UserMapper;
import com.health.healthproject.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public User login(String userPhone, String password) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserPhone, userPhone);
        User user = userMapper.selectOne(wrapper);

        if (user != null && SaSecureUtil.md5(password).equals(user.getPassword())) {
            // 密码正确，返回用户信息（密码置空）
            user.setPassword(null);
            return user;
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String updatePassword(Long id, String oldPassword, String newPassword) {
        User user = userMapper.selectById(id);
        if (user == null) {
            return "用户不存在";
        }

        // 验证旧密码
        if (!SaSecureUtil.md5(oldPassword).equals(user.getPassword())) {
            return "旧密码不正确";
        }

        // 检查新密码是否与旧密码相同
        if (oldPassword.equals(newPassword)) {
            return "新密码不能与旧密码相同";
        }

        // 更新新密码
        User updateUser = new User();
        updateUser.setId(id);
        updateUser.setPassword(SaSecureUtil.md5(newPassword));
        return userMapper.updateById(updateUser) > 0 ? "SUCCESS" : "密码更新失败，请稍后重试";
    }

    @Override
    public Page<User> queryUserPage(Page<User> page, User user) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();

        // 添加查询条件
        wrapper.like(StringUtils.hasText(user.getUserName()), User::getUserName, user.getUserName())
                .eq(user.getUserType() != null, User::getUserType, user.getUserType())
                .eq(user.getStatus() != null, User::getStatus, user.getStatus())
                .ne(User::getStatus,5)
                .orderByDesc(User::getUpdateTime);
        if (StringUtils.hasLength(user.getUserPhone())){
            wrapper.like(User::getUserPhone,user.getUserPhone());
        }
        if (StringUtils.hasLength(user.getUserName())){
            wrapper.like(User::getUserName,user.getUserName());
        }
        if (StringUtils.hasLength(user.getEmergencyContact())){
            wrapper.like(User::getEmergencyContact,user.getEmergencyContact());
        }
        if (StringUtils.hasLength(user.getEmergencyPhone())){
            wrapper.like(User::getEmergencyPhone,user.getEmergencyPhone());
        }
        return userMapper.selectPage(page, wrapper);
    }

    @Override
    public User getUserById(Long id) {
        User user = userMapper.selectById(id);
        if (user != null) {
            user.setPassword(null); // 返回时不携带密码
        }
        return user;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteUser(Long id) {
        User user = userMapper.selectById(id);
        if (null != user){
            user.setStatus(5);
            userMapper.updateById(user);
            return true;
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public User insertUser(User user) {
        // 校验手机号和身份证是否已存在
        LambdaQueryWrapper<User> phoneWrapper = new LambdaQueryWrapper<>();
        phoneWrapper.eq(User::getUserPhone, user.getUserPhone());
        if (userMapper.selectCount(phoneWrapper) > 0) {
            throw new RuntimeException("手机号已存在");
        }

        LambdaQueryWrapper<User> idCardWrapper = new LambdaQueryWrapper<>();
        idCardWrapper.eq(User::getIdCard, user.getIdCard());
        if (userMapper.selectCount(idCardWrapper) > 0) {
            throw new RuntimeException("身份证号已存在");
        }

        // 根据用户类型设置默认密码
        if (user.getUserType() == 2) { // 服务人员
            user.setPassword(SaSecureUtil.md5("123456"));
        } else if (user.getUserType() == 1) { // 空巢老人
            String md5Password = SaSecureUtil.md5(user.getPassword());
            user.setPassword(md5Password);
        }

        // 插入用户
        userMapper.insert(user);

        // 返回插入后的用户信息（不包含密码）
        user.setPassword(null);
        return user;
    }

    @Override
    public Page<User> getUserListByType(Page<User> page, int userType, String userPhone) {
        LambdaQueryWrapper<User> eq = new LambdaQueryWrapper<User>()
                .eq(User::getUserType, userType)
                .ne(User::getStatus,5);
        if (StringUtils.hasLength(userPhone)){
            eq.like(User::getUserPhone,userPhone);
        }
        return userMapper.selectPage(page, eq);
    }


    @Override
    public User updateUser(User user) {
        User user1 = userMapper.selectById(user.getId());
        if (null != user1){
            user1.setUserName(user.getUserName());
            user1.setUserType(user.getUserType());
            user1.setBirthday(user.getBirthday());
            user1.setAddress(user.getAddress());
            user1.setSex(user.getSex());
            user1.setUserPhone(user.getUserPhone());
            user1.setIdCard(user.getIdCard());
            user1.setEmergencyContact(user.getEmergencyContact());
            user1.setEmergencyPhone(user.getEmergencyPhone());
            user1.setEmergencyRelation(user.getEmergencyRelation());
            user1.setStatus(user.getStatus());
            user1.setUserAuth(user.getUserAuth());
            userMapper.updateById(user1);
            return user1;
        }
        return null;
    }
}